package com.ddyx.common.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;

public class ImageIOUtil {

	/**
	 * 获取远程图片的二进制数据
	 * @param filePath
	 * @return
	 */
	public static byte[] getImageBinary(String filePath) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			String prefix = filePath.substring(0, 4);
			BufferedImage bi = null;
			if("http".equalsIgnoreCase(prefix)) {
				bi = ImageIO.read(new URL(filePath));
			} else {
				bi = ImageIO.read(new File(filePath));
			}
			ImageIO.write(bi, "jpg", baos);
			baos.flush();
			return baos.toByteArray();
		} catch(Exception err) {
			err.printStackTrace();
		} finally {
			try {
				baos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}
	
	public static BufferedImage getBufferedImage(String filePath) {
		try {
			String prefix = filePath.substring(0, 4);
			if("http".equalsIgnoreCase(prefix)) {
				return ImageIO.read(new URL(filePath));
			} else {
				return ImageIO.read(new File(filePath));
			}
		} catch(Exception err) {
			err.printStackTrace();
		}
		return null;
	}
}
